using vue0701.Application.Services;
using vue0701.Domain.Entities.App;
using vue0701.Application.DTOs;
using Microsoft.AspNetCore.Mvc;
using vue0701.Domain.Reposoitiories;

namespace vue0701.Api.Controllers;

[ApiController]
[Route("api/[controller]")]
public class UserController : ControllerBase
{
    private readonly UserService _userService;
    private readonly IRepository<AppRole> _roleRepo;

    public UserController(UserService userService, IRepository<AppRole> roleRepo)
    {
        _userService = userService;
        _roleRepo = roleRepo;
    }

    [HttpPost]
    public async Task<IActionResult> Create([FromBody] CreateUserDto dto)
    {
        var user = await _userService.CreateUserAsync(dto.UserName, dto.Password);
        return Ok(new { user.Id, user.UserName });
    }

    [HttpPut("{id}/password")]
    public async Task<IActionResult> ChangePassword(Guid id, [FromBody] ChangePasswordDto dto)
    {
        await _userService.ChangePasswordAsync(id, dto.NewPassword);
        return Ok();
    }

    [HttpPut("{userId}/assign-role")]
    public async Task<IActionResult> AssignRole(Guid userId, [FromBody] AssignRoleDto dto)
    {
        // var role = new AppRole(dto.RoleName); // 这里只做演示，实际应通过仓储获取角色
        // await _userService.AssignRoleAsync(id, role);
        // 正确：应通过仓储查找
        var role = await _roleRepo.GetByIdAsync(dto.roleId); // 或通过Name查找
        if (role == null) throw new Exception("角色不存在");
        await _userService.AssignRoleAsync(userId, role);
        return Ok();
    }

    [HttpPut("{id}/remove-role")]
    public async Task<IActionResult> RemoveRole(Guid id, [FromBody] AssignRoleDto dto)
    {
        var role = await _roleRepo.GetByIdAsync(dto.roleId); // 或通过Name查找
        if (role == null) throw new Exception("角色不存在");
        await _userService.RemoveRoleAsync(id, role);
        return Ok();
    }

    [HttpGet("{id}")]
    public async Task<IActionResult> GetById(Guid id)
    {
        var user = await _userService.GetUserByIdAsync(id);
        if (user == null) return NotFound();
        return Ok(new UserDto(user.Id, user.UserName));
    }

    [HttpGet]
    public async Task<IActionResult> GetAll()
    {
        var users = await _userService.GetAllUsersAsync();
        return Ok(users.Select(u => new UserDto(u.Id, u.UserName)));
    }

    // DTO已迁移至Admin2025.Application.DTOs命名空间
}
